package fu.k4c.vTeam.Search;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Main.BaseActivity;
import fu.k4c.vTeam.Object.AllInformationPlace;
import fu.k4c.vTeam.Object.EventDetails;
import fu.k4c.vTeam.Object.MyLocation;
import fu.k4c.vTeam.Object.PlaceDetails;
import fu.k4c.vTeam.Object.MyLocation.LocationResult;
import fu.k4c.vTeam.ViewDetails.EventTabLayoutActivity;
import fu.k4c.vTeam.ViewDetails.PlaceTabLayoutActivity;

public class ScanActivity extends BaseActivity {
	String categories;
	String distan;
	String status;
	String email;
	int CURRENT_TAG = 0;
	static final int TAG_GUEST = 0;
	static final int TAG_USER = 1;
	private DisplayImageOptions options;
	GridView gv_scan;
	GridView gv_scan2;
	Spinner Distspinner;
	Spinner CateSpinner;
	ProgressDialog proDialog;
	String slat, slong;
	String category[] = { "Ẩm thực", "Bệnh viện", "Cà phê", "Mua sắm",
			"Trạm xăng", "Giải trí", "ATM", "Sự kiện" };
	String distance[] = { "1 km", "2 km", "3 km", "4 km", "5 km", "6 km",
			"7 km" };

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scan);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.stub_image)
				.showImageForEmptyUri(R.drawable.image_for_empty_url)
				.cacheInMemory().cacheOnDisc()
				.displayer(new RoundedBitmapDisplayer(20)).build();
		Bundle data = getIntent().getExtras();
		try {
			if (data != null) {
				status = data.getString("status");
				email = data.getString("email");

			}
			if (status.equals("True")) {
				CURRENT_TAG = TAG_USER;
			} else {
				CURRENT_TAG = TAG_GUEST;
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), e.toString(),
					Toast.LENGTH_LONG).show();
		}
		LocationResult locationResult = new LocationResult() {
			@Override
			public void gotLocation(Location location) {
				// Got the location!
				if (location != null) {
					try {
						slat = "" + location.getLatitude();
						slong = "" + location.getLongitude();
					} catch (Exception e) {
						// TODO: handle exception
						Toast.makeText(getApplicationContext(),
								"Không xác định được địa điểm",
								Toast.LENGTH_LONG).show();
					}
				} else {
					runOnUiThread(new Runnable() {
						public void run() {
							Toast.makeText(getApplicationContext(),
									"Không xác định được địa điểm",
									Toast.LENGTH_LONG).show();
							finish();
						}
					});
				}

			}
		};
		proDialog = ProgressDialog.show(ScanActivity.this, "",
				"Đang xác định địa điểm hiện tại ...");
		new Thread() {
			public void run() {

				try {
					sleep(3000);
				} catch (Exception e) {
					System.out.print(e.toString());
				}
				// dismiss the progressdialog
				proDialog.dismiss();
			}
		}.start();
		MyLocation myLocation = new MyLocation();
		myLocation.getLocation(this, locationResult);
		Button btn_search = (Button) findViewById(R.id.btn_scan_submit);
		btn_search.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				new AsyncTask<Void, Void, Void>() {
					List<AllInformationPlace> yourClassList;
					boolean tmp = false;
					@Override
					protected Void doInBackground(Void... params) {
						// TODO Auto-generated method stub
								try {
									SchemeRegistry registry = new SchemeRegistry();
									registry.register(new Scheme("http",
											PlainSocketFactory
													.getSocketFactory(), 80));
									HttpParams httpParams = new BasicHttpParams();
									ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
											httpParams, registry);
									HttpClient client = new DefaultHttpClient(
											connMgr, httpParams);
									HttpPost post = new HttpPost(
											getString(R.string.connectionString)
													+ "vLocationService/SearchByDistance");
									post.setHeader("Accept", "application/json");
									post.setHeader("Content-type",
											"application/json");
									HashMap<String, Object> postParameters = new HashMap<String, Object>();
									postParameters.put("categorieName",
											categories);
									postParameters.put("distance", distan);
									postParameters.put("lat1", slat);
									postParameters.put("long1", slong);
									postParameters.put("email", email);
									Gson gson = new Gson();
									String jsonParameters = gson
											.toJson(postParameters);
									post.setEntity(new StringEntity(
											jsonParameters));
									HttpResponse response = client
											.execute(post);
									HttpEntity entity = response.getEntity();
									String jsonresult = EntityUtils
											.toString(entity);
									try {
										Type listType = new TypeToken<ArrayList<AllInformationPlace>>() {
										}.getType();
										yourClassList = new Gson()
												.fromJson(jsonresult, listType);
										if (yourClassList.size() == 0) {
											tmp = true;
										}


									} catch (Exception e) {
										// TODO: handle exception
									}

								} catch (Exception e) {
									// TODO: handle exception
								}

						return null;
					}

					protected void onPostExecute(Void result) {

						proDialog.dismiss();
						if(tmp)
						{

							Toast.makeText(
									getApplicationContext(),
									"Không tìm được kết quả nào theo yêu cầu",
									Toast.LENGTH_LONG).show();
						}
						else
						{
							ListCategoriesView adapter = new ListCategoriesView(
									ScanActivity.this,
									yourClassList);
							gv_scan.setAdapter(adapter);
							gv_scan.setOnItemClickListener(new OnItemClickListener() {
								public void onItemClick(
										AdapterView<?> arg0,
										View v, int position,
										long id) {
									if (yourClassList.get(position)
											.getCategoriesID()
											.equals("196")) {
										SchemeRegistry registry = new SchemeRegistry();
										registry.register(new Scheme(
												"http",
												PlainSocketFactory
														.getSocketFactory(),
												80));
										HttpParams httpParams = new BasicHttpParams();
										ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
												httpParams,
												registry);
										HttpClient client = new DefaultHttpClient(
												connMgr, httpParams);
										HttpPost post = new HttpPost(
												getString(R.string.connectionString)
														+ "vLocationService/getdetailevent");
										post.setHeader("Accept",
												"application/json");
										post.setHeader(
												"Content-type",
												"application/json");
										HashMap<String, Object> postParameters = new HashMap<String, Object>();
										// Toast.makeText(getApplicationContext(),yourClassList.get(position).getAddress(),
										// Toast.LENGTH_LONG).show();
										postParameters
												.put("IDofItemRevision",
														yourClassList
																.get(position)
																.getIdPlace());
										postParameters.put(
												"username", email);
										Gson gson = new Gson();
										try {
											String jsonParameters = gson
													.toJson(postParameters);
											post.setEntity(new StringEntity(
													jsonParameters));
											HttpResponse response = client
													.execute(post);
											HttpEntity entity = response
													.getEntity();
											String jsonresult = EntityUtils
													.toString(entity);
											EventDetails mDetails = gson
													.fromJson(
															jsonresult,
															EventDetails.class);
											Intent i = new Intent(
													ScanActivity.this,
													EventTabLayoutActivity.class);
											// Toast.makeText(getApplicationContext(),""+mDetails.isReLike(),
											// Toast.LENGTH_LONG).show();
											i.putExtra(
													"address",
													""
															+ yourClassList
																	.get(position)
																	.getAddress());
											i.putExtra(
													"placename",
													mDetails.getReName());
											i.putExtra(
													"placetel",
													mDetails.getRePhone());
											i.putExtra(
													"likenumber",
													mDetails.getReslVote());
											i.putExtra(
													"visitnumber",
													mDetails.getReslVisit());
											i.putExtra(
													"createby",
													mDetails.getReCreatBy());
											i.putExtra(
													"des",
													mDetails.getReDescription());
											i.putExtra(
													"lat",
													mDetails.getRelat());
											i.putExtra(
													"long",
													mDetails.getRelong());
											i.putExtra(
													"visit",
													mDetails.isReDaDen());
											i.putExtra(
													"like",
													mDetails.isReLike());
											i.putExtra(
													"begin",
													mDetails.getStartDate());
											i.putExtra(
													"end",
													mDetails.getEndDate());
											i.putExtra(
													"IDofItemRevision",
													yourClassList
															.get(position)
															.getIdPlace());
											i.putExtra(
													"views",
													""
															+ mDetails
																	.getSolgnguoiview());
											i.putExtra(
													"avatar",
													""
															+ mDetails
																	.getImageUrl());
											i.putExtra(
													"createbyemail",
													""
															+ mDetails
																	.getEmail());
											if (CURRENT_TAG == TAG_USER) {
												i.putExtra(
														"username",
														email);
											} else {
												i.putExtra(
														"username",
														"Guest");
											}
											startActivity(i);
										} catch (Exception e) {
											// TODO: handle
											// exception
											Toast.makeText(
													getApplicationContext(),
													e.toString(),
													Toast.LENGTH_LONG)
													.show();
										}
									} else {
										SchemeRegistry registry = new SchemeRegistry();
										registry.register(new Scheme(
												"http",
												PlainSocketFactory
														.getSocketFactory(),
												80));
										HttpParams httpParams = new BasicHttpParams();
										ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
												httpParams,
												registry);
										HttpClient client = new DefaultHttpClient(
												connMgr, httpParams);
										HttpPost post = new HttpPost(
												getString(R.string.connectionString)
														+ "vLocationService/GetDetailLocation");
										post.setHeader("Accept",
												"application/json");
										post.setHeader(
												"Content-type",
												"application/json");
										HashMap<String, Object> postParameters = new HashMap<String, Object>();
										postParameters
												.put("IDofItemRevision",
														yourClassList
																.get(position)
																.getIdPlace());
										postParameters.put(
												"username", email);
										// Toast.makeText(getApplicationContext(),"ID la :"+yourClassList.get(position).getIdPlace(),
										// Toast.LENGTH_LONG).show();

										Gson gson = new Gson();
										try {
											String jsonParameters = gson
													.toJson(postParameters);
											post.setEntity(new StringEntity(
													jsonParameters));
											HttpResponse response = client
													.execute(post);
											HttpEntity entity = response
													.getEntity();
											String jsonresult = EntityUtils
													.toString(entity);
											PlaceDetails mDetails = gson
													.fromJson(
															jsonresult,
															PlaceDetails.class);
											Intent i = new Intent(
													ScanActivity.this,
													PlaceTabLayoutActivity.class);
											// Toast.makeText(getApplicationContext(),""+mDetails.isReLike(),
											// Toast.LENGTH_LONG).show();
											i.putExtra(
													"address",
													""
															+ yourClassList
																	.get(position)
																	.getAddress());
											i.putExtra(
													"placename",
													mDetails.getReName());
											i.putExtra(
													"placetel",
													mDetails.getRePhone());
											i.putExtra(
													"likenumber",
													mDetails.getReslVote());
											i.putExtra(
													"visitnumber",
													mDetails.getReslVisit());
											i.putExtra(
													"createby",
													mDetails.getReCreatBy());
											i.putExtra(
													"des",
													mDetails.getReDescription());
											i.putExtra(
													"lat",
													mDetails.getRelat());
											i.putExtra(
													"long",
													mDetails.getRelong());
											i.putExtra(
													"visit",
													mDetails.isReDaDen());
											i.putExtra(
													"like",
													mDetails.isReLike());
											i.putExtra(
													"IDofItemRevision",
													yourClassList
															.get(position)
															.getIdPlace());
											i.putExtra(
													"views",
													""
															+ mDetails
																	.getSolgnguoiview());
											i.putExtra(
													"createbyemail",
													""
															+ mDetails
																	.getEmail());
											if (CURRENT_TAG == TAG_USER) {
												i.putExtra(
														"username",
														email);
											} else {
												i.putExtra(
														"username",
														"Guest");
											}
											startActivity(i);

										} catch (Exception e) {
											// TODO: handle
											// exception
											Toast.makeText(
													getApplicationContext(),
													e.toString(),
													Toast.LENGTH_LONG)
													.show();
										}
									}
								}
							});
						}
					};

					protected void onPreExecute() {
						proDialog = new ProgressDialog(ScanActivity.this);
						proDialog.setMessage("Đang tải dữ liệu...");
						proDialog.setCancelable(false);
						proDialog.show();
					};

					protected void onProgressUpdate(Void... values) {
					}

				}.execute();

			}
		});
		Button btn_back = (Button) findViewById(R.id.btn_scan_back);
		btn_back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		gv_scan = (GridView) findViewById(R.id.gv_scan);
		CateSpinner = (Spinner) findViewById(R.id.sp_scan_category);
		Distspinner = (Spinner) findViewById(R.id.sp_scan_distance);
		ArrayAdapter<String> spinnerArrayAdapter1 = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, category);
		spinnerArrayAdapter1
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		CateSpinner.setAdapter(spinnerArrayAdapter1);
		ArrayAdapter<String> spinnerArrayAdapter2 = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, distance);
		spinnerArrayAdapter2
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		Distspinner.setAdapter(spinnerArrayAdapter2);
		CateSpinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						Object item = parent.getItemAtPosition(pos);
						String catechoise = item.toString();
						if (catechoise.equals("Ẩm thực")) {
							categories = "amthuc";
						} else if (catechoise.equals("Bệnh viện")) {
							categories = "benhvien";
						} else if (catechoise.equals("Cà phê")) {
							categories = "cafe";
						} else if (catechoise.equals("Mua sắm")) {
							categories = "shopping";
						} else if (catechoise.equals("Trạm xăng")) {
							categories = "tramxang";
						} else if (catechoise.equals("Giải trí")) {
							categories = "giaitri";
						} else if (catechoise.equals("ATM")) {
							categories = "atm";
						} else {
							categories = "sukien";
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
		Distspinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						Object item = parent.getItemAtPosition(pos);
						String catechoise = item.toString();
						if (catechoise.equals("1 km")) {
							distan = "1";
						} else if (catechoise.equals("2 km")) {
							distan = "2";
						} else if (catechoise.equals("3 km")) {
							distan = "3";
						} else if (catechoise.equals("4 km")) {
							distan = "4";
						} else if (catechoise.equals("5 km")) {
							distan = "5";
						} else if (catechoise.equals("6 km")) {
							distan = "6";
						} else {
							distan = "7";
						}
					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
	}

	public class ListCategoriesView extends BaseAdapter {
		Activity ListCategoriesView;
		List<AllInformationPlace> data;
		LayoutInflater inflater = null;

		private class ViewHolder {
			public TextView tv_name;
			public TextView tv_phone;
			public TextView tv_address;
			public TextView tv_view;
			public ImageView imv_avatar;
		}

		public ListCategoriesView(Activity mListCategoriesView,
				List<AllInformationPlace> mdata) {
			ListCategoriesView = mListCategoriesView;
			data = mdata;
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return data.get(position);
		}

		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		public View getView(int position, View convertView, ViewGroup arg2) {
			// TODO Auto-generated method stub
			View view = convertView;
			final ViewHolder holder;
			if (convertView == null) {
				view = getLayoutInflater().inflate(
						R.layout.row_view_by_categories, null);
				holder = new ViewHolder();
				holder.imv_avatar = (ImageView) view
						.findViewById(R.id.imv_row_view);
				holder.tv_name = (TextView) view
						.findViewById(R.id.tv_row_view_name);
				holder.tv_phone = (TextView) view
						.findViewById(R.id.tv_row_view_phone);
				holder.tv_address = (TextView) view
						.findViewById(R.id.tv_row_view_address);
				holder.tv_view = (TextView) view
						.findViewById(R.id.tv_row_view_views);
				view.setTag(holder);
			} else
				holder = (ViewHolder) view.getTag();

			String imageurl;
			if (data.get(position).getAvatar() != null) {
				if (data.get(position).getAvatar().toLowerCase()
						.indexOf("http://") >= 0) {
					imageurl = data.get(position).getAvatar();

				} else {
					imageurl = getString(R.string.connectionString)
							+ data.get(position).getAvatar();
				}
			} else {
				imageurl = data.get(position).getAvatar();
			}
			imageLoader.init(ImageLoaderConfiguration
					.createDefault(getBaseContext()));
			imageLoader.displayImage(imageurl, holder.imv_avatar, options,
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(Bitmap loadedImage) {
							Animation anim = AnimationUtils.loadAnimation(
									ScanActivity.this, R.anim.fade_in);
							holder.imv_avatar.setAnimation(anim);
							anim.start();
						}
					});
			holder.tv_name.setText(data.get(position).getName());
			if (data.get(position).getPhone() == null) {
				holder.tv_phone.setText("Số điện thoại : N\\A");
			} else
				holder.tv_phone.setText("Số điện thoại : "
						+ data.get(position).getPhone());
			holder.tv_address.setText("Địa chỉ : "
					+ data.get(position).getAddress());
			holder.tv_view.setText("Lượt xem : "
					+ data.get(position).getViews());
			return view;
		}
	}
}
